/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import ejb.CategoryBeanLocal;
import ejb.ProductBeanLocal;
import entities.Category;
import entities.Product;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import web.models.ProductModel;

/**
 *
 * @author Jesus
 */
@ManagedBean
public class AdvSearchBean {

    @EJB
    private ProductBeanLocal productBean;
    @EJB
    private CategoryBeanLocal categoryBean;
    private ProductModel productsModel;
    private List<Product> results;
    private Product selectedProduct;
    private SelectItem[] categories;

    public AdvSearchBean() {
    }

    @PostConstruct
    public void init() {
        productsModel = new ProductModel(productBean.findAll());
        initCategories();

    }

    public Product getSelectedProduct() {
        return selectedProduct;
    }

    public void setSelectedProduct(Product selectedProduct) {
        this.selectedProduct = selectedProduct;
    }

    public List<Product> getResults() {
        return results;
    }

    public void setResults(List<Product> results) {
        this.results = results;
    }

    public ProductModel getProductsModel() {
        return productsModel;
    }

    public void setProductsModel(ProductModel productsModel) {
        this.productsModel = productsModel;
    }

    public SelectItem[] getCategories() {
        return categories;
    }

    public void setCategories(SelectItem[] categories) {
        this.categories = categories;
    }

    public void goToProduct(Long id) {
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("/Tiendalia-war/tiendalia/product.xhtml?product=" + id.toString());
        } catch (IOException ex) {
            Logger.getLogger(AdvSearchBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void initCategories() {
        List<Category> cats = categoryBean.findAll();
        SelectItem[] siCats = new SelectItem[cats.size() + 1];
        siCats[0] = new SelectItem("", "Selecciona");
        for (int i = 0; i < siCats.length - 1; i++) {
            siCats[i + 1] = new SelectItem(cats.get(i).getName());
        }
        categories = siCats;
    }
}
